package com.polaris.live.manager

import android.text.TextUtils
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import java.util.concurrent.TimeUnit

/**
 * 下载相关
 *
 * todo 需要接入真实的大文件下载
 *
 * @author Created by lucas on 2023/10/25 20:28
 */
object DownloadManager {

    private val mOkHttpClient: OkHttpClient by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
        OkHttpClient.Builder()
            .callTimeout(5, TimeUnit.SECONDS)
            .followRedirects(true)
            .build()
    }

    /**
     * 简单的下载，不能用来下载大文件
     */
    suspend fun downloadSimple(url: String): String {
        return withContext(Dispatchers.IO) {
            CompletableDeferred<String>().apply {
                val request = Request.Builder()
                    .url(url)
                    .build()

                mOkHttpClient.newCall(request)
                    .enqueue(object : Callback {
                        override fun onFailure(call: Call, e: IOException) {
                            completeExceptionally(e)
                        }

                        override fun onResponse(call: Call, response: Response) {
                            response.use {
                                if (response.isSuccessful) {
                                    val body = it.body
                                    if (body == null) {
                                        completeExceptionally(DownloadException("文件下载失败，无法解析！"))
                                        return
                                    }
                                    try {
                                        val html = body.string()
                                        if (TextUtils.isEmpty(html)) {
                                            completeExceptionally(DownloadException("文件下载失败，内容为空！"))
                                            return
                                        }

                                        complete(html)
                                    } catch (e: Exception) {
                                        completeExceptionally(e)
                                    }
                                } else {
                                    completeExceptionally(DownloadException("文件下载失败，请检查网络！"))
                                }
                            }
                        }
                    })
            }.await()
        }
    }
}

class DownloadException(message: String) : Exception(message)